<?php
namespace App\Task;

use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * @Crontab(
 *     rule="5,10,15,20,25,30,35,40,45,50,55 * * * *",
 *     name="AutoPublishBlog",
 *     callback="execute",
 *     memo="每5分钟处理博客",
 *     singleton=true
 * )
 */
class AutoPublishBlogs
{
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('article', 'article');
    }

    public function execute()
    {
        $this->logger->info("====== 测试日志 ======");

        try {
            // 1. 从default数据库获取5条待处理记录
            $logs = Db::connection('default')
                ->table('blogs_log')
                ->orderBy('id')
                ->limit(5)
                ->get();

            if ($logs->isEmpty()) {
                $this->logger->info("没有待处理的博客记录");
                return;
            }

            // 2. 按webname分组处理
            $processed = [];
            foreach ($logs as $log) {
                try {
                    // 3. 更新对应数据库的oc_blog表
                    $updated = Db::connection($log->webname)
                        ->table('oc_blog')
                        ->where('blog_id', $log->blog_id)
                        ->update([
                            'status' => 1,
                            'date_added' => date('Y-m-d H:i:s')
                        ]);

                    if ($updated) {
                        // 记录成功处理的ID
                        $processed[] = $log->id;
                        $this->logger->info("成功发布博客: {$log->webname} - {$log->blog_id}");
                    }
                } catch (\Throwable $e) {
                    $this->logger->error("处理博客失败[{$log->webname}-{$log->blog_id}]: " . $e->getMessage());
                }
            }

            // 4. 删除已处理的记录
            if (!empty($processed)) {
                Db::connection('default')
                    ->table('blogs_log')
                    ->whereIn('id', $processed)
                    ->delete();

                $this->logger->info("已清理".count($processed)."条处理完成的记录");
            }

        } catch (\Throwable $e) {
            $this->logger->error("任务执行失败: " . $e->getMessage());
        }
    }
}
